package generate

import (
	"io"
	"log"
	"os"
	"os/exec"
	"strings"

	"gormx/dbtools"

	c "gormx/conf"

	"github.com/golang/protobuf/protoc-gen-go/generator"
)

// 获取表信息
func getTables(tableNames string) []Table {
	db := dbtools.GetMysqlDb()
	var tables []Table
	if tableNames == "" {
		db.Raw("SELECT TABLE_NAME as Name,TABLE_COMMENT as Comment FROM information_schema.TABLES WHERE table_schema='" + c.Con.DBInfo.DbName + "';").Find(&tables)
	} else {
		db.Raw("SELECT TABLE_NAME as Name,TABLE_COMMENT as Comment FROM information_schema.TABLES WHERE TABLE_NAME IN (" + tableNames + ") AND table_schema='" + c.Con.DBInfo.DbName + "';").Find(&tables)
	}
	return tables
}

// 获取所有字段信息
func getFields(tableName string) []Field {
	db := dbtools.GetMysqlDb()
	var fields []Field
	db.Raw("show FULL COLUMNS from " + tableName + ";").Find(&fields)
	return fields
}

// 获取字段类型
func getFiledType(field Field) string {
	typeArr := strings.Split(field.Type, "(")

	switch typeArr[0] {
	case "int":
		return "int"
	case "integer":
		return "int"
	case "mediumint":
		return "int"
	case "bit":
		return "int"
	case "year":
		return "int"
	case "smallint":
		return "int"
	case "tinyint":
		return "int"
	case "bigint":
		return "int64"
	case "decimal":
		return "float64"
	case "double":
		return "float64"
	case "float":
		return "float64"
	case "real":
		return "float32"
	case "numeric":
		return "float64"
	case "timestamp":
		return "time.Time"
	case "datetime":
		return "time.Time"
	case "time":
		return "time.Time"
	default:
		return "string"
	}
}

// 获取字段json描述
func getFieldJson(field Field) string {
	return `json:"` + generator.CamelCase(strings.ToLower(field.Field)) + `"`
}

// 获取字段gorm描述
func getFieldOrm(field Field) string {
	if field.Null == "NO" {
		return `gorm:"column:` + field.Field + ";type:" + field.Type + ";not null" + `"`
	} else {
		return `gorm:"column:` + field.Field + ";type:" + field.Type + `"`
	}

}

// 获取字段说明
func getFieldComment(field Field) string {
	if len(field.Comment) > 0 {
		return "// " + field.Comment
	}
	return ""
}

// 检查文件是否存在
func checkFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}

// Case2Camel 下划线写法转为驼峰写法
func Case2Camel(name string) string {
	name = strings.Replace(name, "_", " ", -1)
	name = strings.Title(name)
	return strings.Replace(name, " ", "", -1)
}

// FirstUpper 字符串首字母大写
func FirstUpper(s string) string {
	if s == "" {
		return ""
	}
	return strings.ToUpper(s[:1]) + s[1:]
}

// FirstLower FirstUpper 字符串首字母小写
func FirstLower(s string) string {
	if s == "" {
		return ""
	}
	return strings.ToLower(s[:1]) + s[1:]
}

func makeFile(content, filename string) {
	filename = c.ModelPath + filename + ".go"
	var f *os.File
	var err error
	if checkFileIsExist(filename) {
		f, err = os.OpenFile(filename, os.O_WRONLY|os.O_TRUNC, 0666) // 打开文件
		if err != nil {
			panic(err)
		}
	} else {
		// 创建目录
		os.Mkdir(c.ModelPath, os.ModePerm)
		f, err = os.OpenFile(filename, os.O_CREATE|os.O_EXCL, 0777)
		if err != nil {
			panic(err)
		}
	}
	defer f.Close()
	_, err = io.WriteString(f, content)
	if err != nil {
		panic(err)
	} else {
		// 导入 需要的系统 包
		var err error
		_, err = exec.Command("gofmt", "-l", "-w", filename).Output()
		if err != nil {
			log.Println(err)
		}
		_, err = exec.Command("goimports", "-l", "-w", filename).Output()
		if err != nil {
			log.Println(err)
		}
	}
}
